import {defineStore} from 'pinia';
import {getAssetList} from '@/api/user/asset.js';
import {useUserStore} from '@/stores/user/user.js'

export const useAssetStore = defineStore('asset', {
    state: () => ({
        assetList: [],
        total: 0,
        queryParams: {
            page: 1,
            pageSize: 10,
            assetName: '',
            categoryName: '',
            statusName: '',
        },
        loading: false,
    }),
    getters: {
        availableAssetsCount: (state) => {
            return state.assetList.filter(asset => asset.status === '在库').length;
        },
    },
    actions: {
        // 获取资产列表数据
        async getAssets() {
            this.loading = true;
            try {
                const response = await getAssetList({
                    page: this.queryParams.page,
                    pageSize: this.queryParams.pageSize,
                    assetName: this.queryParams.assetName,
                    categoryName: this.queryParams.categoryName,
                    statusName: this.queryParams.statusName,
                });
                if (response.code === 200) {
                    const userStore = useUserStore();
                    let processedRecords = response.data.records;
                    if (userStore.role !== 'admin') {
                        processedRecords = response.data.records.map(item => {
                            const {purchasePrice, ...assetWithoutPrice} = item;
                            return assetWithoutPrice;
                        })
                    }
                    this.assetList = response.data.records;
                    this.total = response.data.total;
                } else {
                    Element.error({message: "获取资产列表失败", duration: 3000});
                    console.error(response.message || '获取资产列表失败');
                }
            } catch (error) {
                Element.error({message: "获取资产列表失败", duration: 3000});
                console.error(error.message || '获取资产列表失败');
            } finally {
                this.loading = false;
            }
        },
        // 设置当前页码
        setPage(page) {
            this.queryParams.page = page;
        },
        // 设置每页显示记录数
        setPageSize(pageSize) {
            this.queryParams.pageSize = pageSize;
        },

        // 重置查询参数
        resetQuery() {
            this.queryParams.assetName = '';
            this.queryParams.categoryName = '';
            this.queryParams.statusName = '';
            this.queryParams.page = 1;
        }
    },
});